#region (c) 2009 Abdullin.com and Contributors

// Copyright (c) 2009 Abdullin.com and Contributors
// Site: http://abdullin.com/ncouch
// This code is released under the terms of the new BSD licence

#endregion

using System;
using System.Diagnostics;
using System.IO;

namespace NCouch.Rest
{
	public static class RestClientDebugger
	{
		public static void Print(IRestRequest request)
		{
			Debug.WriteLine("Request: "+request.Method + " " + request.RequestUri);

			if (!string.IsNullOrEmpty(request.ContentType))
				Debug.WriteLine("Content type: " + request.ContentType);

			if (request.ContentType == CouchRestClient.JsonContentType)
			{
				request.Content.Apply(PrintStream);
			}
		}

		public static void Print(IRestResponse response)
		{
			
			Debug.WriteLine("Response: " + response.StatusCode);
			Debug.WriteLine("Content: " + response.ContentType + " [" + response.ContentLength + "]");

			if (response.ContentLength > 0)
			{
				response.RunReader(DumpStream);
			}
		}


		static void PrintStream(Action<Stream> writer)
		{
			using (var stream = new RestClientInjectionStream())
			{
				writer(stream);
				stream.Seek(0, SeekOrigin.Begin);
				DumpStream(stream);
				stream.CanBeClosed = true;
			}
		}

		static void DumpStream(Stream stream)
		{
			using (var reader = new StreamReader(stream, true))
			{
				Debug.WriteLine(reader.ReadToEnd());
			}
		}
	}
}